package com.work.blog.utils;

import com.work.blog.constant.Constant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:DELL
 * Date:2025-06-17
 * Time:15:44
 */
//令牌
@Slf4j
public class JwtUtils {

    //1小时后过期
    private static final long JWT_EXPIRATION = 60*60*1000;
    //生成key
    private static final String secretStr ="AKdVdutwigwjmWajeLXyQL2eNz/YSa8v8msoya4vr/M=";
    private static final Key key= Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretStr));

    //生成token
    public static String genJwtToken(Map<String,Object> claim){
        String token = Jwts.builder().setClaims(claim)
                .setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
                .signWith(key)
                .compact();
        return token;
    }

    /*校验token*/
    public static Claims parseToken(String token){
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims=null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("解析token失败，token:{}",token);
            return null;
        }
        return claims;
    }

    //从token中获取id
    public static Integer getIdByToken(String token){
        Claims claims=parseToken(token);
        if (claims!=null){
            Integer userId = (Integer) claims.get(Constant.TOKEN_ID);
            if (userId>0){
                return userId;
            }
        }
        return null;
    }
}
